package servletAction;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.context.ApplicationContext;

import util.DomainUtils;
import util.FormArgumentsException;
import domain.dao.interfaces.IDAOUser;
import actionForm.AddUserValidationForm;

public class AddUserAction extends Action {

	public ActionForward execute(final ActionMapping pMapping,
			ActionForm pForm, final HttpServletRequest pRequest,
			final HttpServletResponse pResponse) {

		ApplicationContext context = util.SpringUtils.getApplicationContext();
		final AddUserValidationForm lForm = (AddUserValidationForm) pForm;

		String login = lForm.getLogin();
		String password = lForm.getPassword();


		try {
			IDAOUser daoUser = (IDAOUser) context.getBean("beanDAOUser");
			daoUser.addUser( login, password);
			

			DomainUtils.displayInfoMessage(
					pRequest, 
					DomainUtils.REGISTER_ALERT_CURRENT_COLOR, 
					"Thank you for register. You can now connect yourself from the home page with the login \""+login+"\".");
		}
		catch(Exception e) {

			if((e instanceof FormArgumentsException) == false) {
				pRequest.setAttribute(DomainUtils.ALERT_ERROR_STRING, "An error occur on the server.");
			}

			DomainUtils.keepParametersContent(pRequest);
		}

		return pMapping.findForward("stay");
	}
}
